package com.yunkaweilai.android.fragment.guadan;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.DensityUtil;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.operation.consumption.guadan.ShopGuadanActivity;
import com.yunkaweilai.android.activity.operation.consumption.room.RoomInfoActivity;
import com.yunkaweilai.android.base.BaseFragment;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.guadan.GuadanListModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.Utils;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * 挂单列表
 * Created by Administrator on 2017/8/4.
 */

public class GuadanFragment extends BaseFragment implements BGARefreshLayout.BGARefreshLayoutDelegate {
    @BindView(R.id.id_listView)
    ListView idListView;
    @BindView(R.id.content_view)
    BGARefreshLayout contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    Unbinder unbinder;
    private int mpage = 1;
    private boolean mHasMore = true;
    private Gson gson = new Gson();
    private ArrayList<GuadanListModel.DataBean.ListBean> list = new ArrayList<>();
    private CommonAdapter<GuadanListModel.DataBean.ListBean> adapter;
    private String is_history = "";
    private String guadan_type = "";
    private String start_time = "";
    private String end_time = "";

    public static GuadanFragment getInstence(String is_history, String guadan_type) {
        GuadanFragment fragment = new GuadanFragment();
        fragment.is_history = is_history;
        fragment.guadan_type = guadan_type;
        return fragment;
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_list_left_slip;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        initRefreshLayout(contentView, this, true);
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp(true);
            }
        });
        idListView.setDividerHeight(DensityUtil.dip2px(mAc, 7));
        initAdapter();
        initClick();
        end_time = Utils.datePlus(0);
        start_time = Utils.datePlus(-30);
        initHttp(true);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void onEvent(Event.TypeEvent event){
        if (event!=null){
            if (event.type == CommonConstants.GUADAN_LIST) {
                initHttp(true);
            }
        }
    }

    private void initClick() {
        idListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GuadanListModel.DataBean.ListBean listBean = list.get(position);
                if ("0".equals(is_history)) {
                    if (Utils.isEmpty(listBean.getGroup_info().getId())) {
                        ShopGuadanActivity.actionSatrt(mAc, listBean.getGid(), listBean.getGroup_id());
                    } else {
                        RoomInfoActivity.actionStart(mAc, listBean.getGid(), listBean.getGroup_info().getTitle(), false);
                    }
                }

            }
        });
    }

    private void initAdapter() {
        adapter = new CommonAdapter<GuadanListModel.DataBean.ListBean>(mAc, R.layout.item_list_guadan, list) {
            @Override
            protected void convert(ViewHolder viewHolder, GuadanListModel.DataBean.ListBean item, int position) {
                TextView timeName = viewHolder.getView(R.id.id_tv_time_name);
                if ("1".equals(is_history)) {
                    timeName.setText("结算时间");
                } else {
                    timeName.setText("挂单时间");
                }
                if (Utils.isEmpty(item.getGroup_info().getId())) {
                    viewHolder.setText(R.id.id_tv_gno, item.getGid() + "(普通)");
                } else {
                    viewHolder.setText(R.id.id_tv_gno, item.getGid() + "(房台)");
                }
                viewHolder.setText(R.id.id_tv_time, item.getCreate_time());
                viewHolder.setText(R.id.id_tv_money, item.getPayment() + "");
                viewHolder.setText(R.id.id_tv_remarks, item.getRemark());
                TextView idTvStatus = viewHolder.getView(R.id.id_tv_status);
                if ("1".equals(is_history)) {
                    idTvStatus.setVisibility(View.VISIBLE);
                    if ("0".equals(item.getStatus())) {
                        idTvStatus.setText("已作废");
                        idTvStatus.setTextColor(getResources().getColor(R.color.wjx_title_bg_next));
                    } else if ("2".equals(item.getStatus())) {
                        idTvStatus.setText("已结算");
                        idTvStatus.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_left));
                    } else {
                        idTvStatus.setText("");
                    }
                } else {
                    idTvStatus.setVisibility(View.GONE);
                }
            }
        };
        idListView.setAdapter(adapter);
    }

    private boolean initHttp(final boolean refresh) {
        mpage = refresh ? 1 : mpage;
        if ((!mHasMore) && (!refresh)) {
            contentView.endLoadingMore();
            showToast("没有更多数据了");
            return false;
        }
        Log.d(TAG, "initHttp: here");
        HttpRequest.postUrl(Api.GUADAN_LIST)
                .addParams("ShowPage", "1")
                .addParams("PageSize", "10")
                .addParams("CurrPage", mpage + "")
                .addParams("is_history", is_history)
//                .addParams("guadan_type","1")
                .addParams("start_time", start_time)
                .addParams("end_time", end_time)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        endRefreshOrLoad(refresh);
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            mpage++;
                            GuadanListModel consumeModel = gson.fromJson(json, GuadanListModel.class);
                            if (refresh) {
                                list.clear();
                            }
                            if (consumeModel.getData().getList() != null && consumeModel.getData().getList().size() != 0) {
                                list.addAll(consumeModel.getData().getList());
                                adapter.notifyDataSetChanged();
                                mHasMore = consumeModel.getData().getPage().isNext();//是否还有下一页
                                //历史挂单返回false，正在挂单返回true
                                EventBus.getDefault().post(new Event.NumTypeEvent(CommonConstants.GUADAN_TITLE_NUM, consumeModel.getData().getPage().getCount(), "0".equals(is_history) ? true : false));
                                if (idMultipleStatusView != null) {
                                    idMultipleStatusView.showContent();
                                }
                            } else {
                                mHasMore = false;
                                if (refresh) {
                                    if (idMultipleStatusView != null) {
                                        idMultipleStatusView.showEmpty();
                                    }
                                }
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });

        return true;
    }

    /**
     * 结束刷新组件
     *
     * @param refresh
     */
    private void endRefreshOrLoad(boolean refresh) {
        if (refresh) {
            if (contentView != null) {
                contentView.endRefreshing();
            }
        } else {
            if (contentView != null) {
                contentView.endLoadingMore();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        initHttp(true);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return initHttp(false);
    }
}
